package com.numberone.master.modules.sys.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.numberone.master.common.service.TreeService;
import com.numberone.master.modules.sys.dao.OfficeDao;
import com.numberone.master.modules.sys.entity.Office;
import com.numberone.master.modules.sys.utils.UserUtils;

/**
 * 机构Service
 * @author numberone
 * @version 2014-05-16
 */
@Service
@Transactional(readOnly = true)
public class OfficeService extends TreeService<OfficeDao, Office> {
	
	@Autowired
	private OfficeDao officeDao;
	
	public List<Office> findAll(){
		return UserUtils.getOfficeList();
	}

	public List<Office> findList(Boolean isAll){
		if (isAll != null && isAll){
			return UserUtils.getOfficeAllList();
		}else{
			return UserUtils.getOfficeList();
		}
	}
	
	@Transactional(readOnly = true)
	public List<Office> findList(Office office){
		if(office != null){
			return dao.findByParentIdsLike(office);
		}
		return  new ArrayList<Office>();
	}
	
	@Transactional(readOnly = false)
	public void save(Office office) {
		super.save(office);
		UserUtils.removeCache(UserUtils.CACHE_OFFICE_LIST);
	}
	
	@Transactional(readOnly = false)
	public void delete(Office office) {
		super.delete(office);
		UserUtils.removeCache(UserUtils.CACHE_OFFICE_LIST);
	}
	
	@Transactional(readOnly = true)
	public List<Office> findAlreadyList(Office office){
			return officeDao.findAlreadyList(office);
	}
	
	@Transactional(readOnly = true)
	public List<Office> findOfficeListByIds(String ids){
			return officeDao.findOfficeListByIds(ids);
	}
	
	public Office isName(String name){
		return officeDao.isName(name);
	}
	
	public Office getAgentByIccid(String iccid){
		return officeDao.getAgentByIccid(iccid);
	}
	
	
	public List<String> getAllOwnAgent(String officeId, List<String> list) {
		List<Office> office = officeDao.getNextOfficeByid(officeId);
		if (office != null) {
			if (office.size() > 0) {
				for (int i = 0; i < office.size(); i++) {
					list.add(office.get(i).getId());
					getAllOwnAgent(office.get(i).getId(), list);
				}
			}
		}
		return list;
	}
}
